package com.fengmi.listener;

import com.api.goods.GoodsApi;
import com.fengmi.goods.entity.MallGoods;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.rocketmq.client.consumer.MessageQueueListener;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

@Component
@RocketMQMessageListener(consumerGroup = "fengmi_html_group",
        topic = "goodsgenHTML",selectorExpression = "*",
        consumeMode = ConsumeMode.CONCURRENTLY,
        messageModel = MessageModel.BROADCASTING)
public class GoodsGenHtmlListener implements RocketMQListener<String> {



    @Autowired
    private FreeMarkerConfig freeMarkerConfig;


    @Autowired
    private GoodsApi goodsApi;

    @Override
    public void onMessage(String spuId)  {
        try {
            //生成静态化页面

            System.out.println(spuId);
            Configuration configuration = freeMarkerConfig.getConfiguration();

            //4.获取模板对象
            Template template = configuration.getTemplate("introduction.ftl");
            //5.创建模型数据

            //获取商品相关的信息
            MallGoods mallGoods = goodsApi.findGoodsForHTML(spuId);


            Map data = new HashMap(){{


                put("specOpts",mallGoods.getSpecAndOptsVOList());

                put("skuList",mallGoods.getSkuList());


            }};
            //6.创建输出流(FileWriter)对象
            Writer out = new FileWriter("E:\\nginx-1.18.0\\goodshtml\\"+spuId+".html");
            //7.输出
            template.process(data,out);
            //8.关闭
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


    }
}
